package com.arvin.faceDetect.ui

import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.arvin.faceDetect.databinding.FragmentRecognitionRecordsBinding
import com.arvin.faceDetect.db.FaceDatabase
import com.arvin.faceDetect.ui.adapter.RecognitionRecordAdapter
import com.arvin.faceDetect.utils.LogUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

class RecognitionRecordsFragment : Fragment() {
    private var _binding: FragmentRecognitionRecordsBinding? = null
    private val binding get() = _binding!!
    
    private lateinit var recordAdapter: RecognitionRecordAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentRecognitionRecordsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupToolbar()
        setupRecyclerView()
        loadRecords()
    }

    private fun setupToolbar() {
        binding.btnExport.setOnClickListener {
            exportRecords()
        }

        binding.btnClear.setOnClickListener {
            showClearConfirmationDialog()
        }
    }

    private fun showClearConfirmationDialog() {
        AlertDialog.Builder(requireContext())
            .setTitle("清除记录")
            .setMessage("确定要清除所有识别记录吗？此操作不可恢复。")
            .setPositiveButton("确定") { _, _ ->
                clearRecords()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun clearRecords() {
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                withContext(Dispatchers.IO) {
                    FaceDatabase.getDatabase(requireContext())
                        .recognitionRecordDao()
                        .deleteAllRecords()
                }
                Toast.makeText(context, "已清除所有记录", Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                LogUtils.e("RecognitionRecords", "清除记录失败", e)
                Toast.makeText(context, "清除失败：${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun exportRecords() {
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                // 获取所有识别记录
                val records = withContext(Dispatchers.IO) {
                    FaceDatabase.getDatabase(requireContext())
                        .recognitionRecordDao()
                        .getAllRecordsAsList()
                }

                if (records.isEmpty()) {
                    Toast.makeText(context, "没有可导出的记录", Toast.LENGTH_SHORT).show()
                    return@launch
                }

                // 创建导出目录
                val timestamp =
                    SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
                val exportDir = File(requireContext().getExternalFilesDir(null), "exports")
                if (!exportDir.exists()) {
                    exportDir.mkdirs()
                }

                // 创建临时目录用于存放导出文件
                val tempDir = File(exportDir, "export_${timestamp}")
                if (!tempDir.exists()) {
                    tempDir.mkdirs()
                }

                // 创建CSV文件
                val csvFile = File(tempDir, "recognition_records.csv")
                withContext(Dispatchers.IO) {
                    csvFile.bufferedWriter().use { writer ->
                        // 写入表头
                        writer.write("姓名,识别时间,相似度,图片文件名\n")

                        // 写入数据并保存图片
                        records.forEachIndexed { index, record ->
                            // 写入CSV数据
                            writer.write(
                                "${record.name},${formatTime(record.recognitionTime)},${
                                    String.format(
                                        "%.2f%%",
                                        record.similarity * 100
                                    )
                                },face_${index + 1}.jpg\n"
                            )

                            // 保存人脸图片
                            record.faceBitmap?.let { bitmap ->
                                val imageFile = File(tempDir, "face_${index + 1}.jpg")
                                imageFile.outputStream().use { output ->
                                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, output)
                                }
                            }
                        }
                    }
                }

//                // 创建Python转换脚本
//                val pythonScript = File(tempDir, "convert_to_xls.py")
//                withContext(Dispatchers.IO) {
//                    pythonScript.writeText("""
//                        import pandas as pd
//                        from openpyxl import Workbook
//                        from openpyxl.drawing.image import Image
//                        import os
//
//                        # 读取CSV文件
//                        df = pd.read_csv('recognition_records.csv')
//
//                        # 创建Excel工作簿
//                        wb = Workbook()
//                        ws = wb.active
//
//                        # 写入表头
//                        headers = ['姓名', '识别时间', '相似度', '人脸图片']
//                        for col, header in enumerate(headers, 1):
//                            ws.cell(row=1, column=col, value=header)
//
//                        # 写入数据
//                        for row_idx, (_, row) in enumerate(df.iterrows(), 2):
//                            # 写入前三列数据
//                            for col_idx, value in enumerate(row[:3], 1):
//                                ws.cell(row=row_idx, column=col_idx, value=value)
//
//                            # 插入图片
//                            img_path = row[3]  # 图片文件名
//                            if os.path.exists(img_path):
//                                img = Image(img_path)
//                                # 设置图片位置和大小
//                                img.width = 100
//                                img.height = 100
//                                ws.add_image(img, f'D{row_idx}')  # 将图片放在D列
//
//                        # 调整列宽
//                        ws.column_dimensions['A'].width = 15  # 姓名
//                        ws.column_dimensions['B'].width = 20  # 识别时间
//                        ws.column_dimensions['C'].width = 15  # 相似度
//                        ws.column_dimensions['D'].width = 20  # 图片
//
//                        # 保存Excel文件
//                        wb.save('recognition_records.xlsx')
//                    """.trimIndent())
//                }

                // 创建说明文件
                val readmeFile = File(tempDir, "README.txt")
                withContext(Dispatchers.IO) {
                    readmeFile.writeText(
                        """
                        如何将CSV转换为带图片的Excel文件：

                        1. 确保您的电脑已安装Python 3.x
                        2. 安装必要的Python包：
                           pip install pandas openpyxl pillow
                        3. 将所有文件解压到同一目录
                        4. 运行Python脚本：
                           python convert_to_xls.py
                        5. 转换完成后，会在同一目录下生成recognition_records.xlsx文件

                        注意：转换过程中需要保持图片文件与CSV文件在同一目录下。
                    """.trimIndent()
                    )
                }

                // 创建ZIP文件
                val zipFile = File(exportDir, "recognition_records_${timestamp}.zip")
                withContext(Dispatchers.IO) {
                    ZipOutputStream(zipFile.outputStream()).use { zip ->
                        tempDir.walkTopDown().forEach { file ->
                            if (file.isFile) {
                                val entry = ZipEntry(file.relativeTo(tempDir).path)
                                zip.putNextEntry(entry)
                                file.inputStream().use { input ->
                                    input.copyTo(zip)
                                }
                                zip.closeEntry()
                            }
                        }
                    }
                }

                // 删除临时目录
                tempDir.deleteRecursively()

                // 分享ZIP文件
                val uri = FileProvider.getUriForFile(
                    requireContext(),
                    "${requireContext().packageName}.provider",
                    zipFile
                )

                val intent = Intent(Intent.ACTION_SEND).apply {
                    type = "application/zip"
                    putExtra(Intent.EXTRA_STREAM, uri)
                    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                }

                startActivity(Intent.createChooser(intent, "分享导出文件"))

                Toast.makeText(
                    context,
                    "导出成功，请查看README文件了解如何转换为Excel",
                    Toast.LENGTH_LONG
                ).show()
            } catch (e: Exception) {
                LogUtils.e("RecognitionRecords", "导出识别记录失败", e)
                Toast.makeText(context, "导出失败：${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun formatTime(timestamp: Long): String {
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        return sdf.format(Date(timestamp))
    }

    private fun setupRecyclerView() {
        recordAdapter = RecognitionRecordAdapter()
        binding.rvRecords.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = recordAdapter
        }
    }

    private fun loadRecords() {
        lifecycleScope.launch {
            FaceDatabase.getDatabase(requireContext())
                .recognitionRecordDao()
                .getAllRecords()
                .collectLatest { records ->
                    recordAdapter.submitList(records)
                }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 